package shortlink.common.web;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import shortlink.common.convention.errorcode.BaseErrorCode;
import shortlink.common.convention.exception.AbstractException;
import shortlink.common.convention.result.Result;
import shortlink.common.convention.result.Results;

import java.util.Optional;

@Slf4j
@Component
@RestControllerAdvice
public class GlobalExceptionHandler {

    /*拦截参数验证异常*/
    @SneakyThrows
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result validExceptionhandler(HttpServletRequest request, MethodArgumentNotValidException ex) {
        BindingResult bindingResult = ex.getBindingResult();
        FieldError fieldError = CollectionUtil.getFirst(bindingResult.getFieldErrors());
        String exceptionStr = Optional.ofNullable(fieldError)
                .map(FieldError::getDefaultMessage)
                .orElse(StrUtil.EMPTY);
        log.error("[{}] {} [ex] {}",request.getMethod(),request.getRequestURI(),exceptionStr);
        return Results.failure(BaseErrorCode.CLIENT_ERROR.code(),exceptionStr);
    }

    /*拦截应用内抛出的异常*/
    @ExceptionHandler(AbstractException.class)
    public  Result abstractExceptionhandler(HttpServletRequest request,AbstractException ex) {
        if(ex.getCause()!=null){
            log.error("[{}] {} [ex] {}",request.getMethod(),request.getRequestURI().toString(),ex.toString(),ex.getCause());
            return Results.failure(ex);
        }
        log.error("[{}] {} [ex] {}", request.getMethod(), request.getRequestURL().toString(), ex.toString());
        return Results.failure(ex);
    }
    /*拦截未捕获异常*/
    @ExceptionHandler(Throwable.class)
    public Result defaultErrorHandler(HttpServletRequest request,Throwable throwable) {
        log.error("[{}] {} ", request.getMethod(), getUrl(request), throwable);
        return Results.failure();
    }

    private String getUrl(HttpServletRequest request) {
        if (StringUtils.isEmpty(request.getQueryString())) {
            return request.getRequestURL().toString();
        }
        return request.getRequestURL().toString() + "?" + request.getQueryString();
    }

}
